package com.bruce.shop.web.back;

import com.alibaba.fastjson.JSON;
import com.bruce.shop.commons.constans.ShopConstants;
import com.bruce.shop.commons.utils.Response;
import com.bruce.shop.commons.web.DispatcherServlet;
import com.bruce.shop.entity.Page;
import com.bruce.shop.entity.User;
import com.bruce.shop.service.UserService;
import com.bruce.shop.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author BruceXia
 * @version 1.0.0
 * @description:对用户相关请求进行处理的控制器
 * @date 2022/9/1719:25
 */
@WebServlet("/UserController/*")
public class UserController extends DispatcherServlet {

    //调用业务层创建一个实例化对象
    private UserService userService = new UserServiceImpl();

    /**
     * 用户查询页面分页的方法
     * @param request
     * @param response
     * @return
     */
    public String userPage(HttpServletRequest request, HttpServletResponse response) {

        // 1.获取前端传递的值
        String curPage = request.getParameter("curPage");
        String size = request.getParameter("size");

        // 2.实例化分页对象
        Page<User> page = new Page<>(); // page中总共有6个属性，
        if (curPage != null && !"".equals(curPage)) {
            page.setCurPage(Integer.parseInt(curPage));
        }
        if (size != null && !"".equals(size)) {
            page.setSize(Integer.parseInt(size));
        }

        // 3.调用业务层把所有的数据全部封装到page对象中
        page.setUrl("UserController/userPage");
        userService.page(page);

        // 4.把page对象添加req作用域中
        request.setAttribute("page", page);

        // 5.跳转到用户列表展示数据
        return ShopConstants.FORWARD + ":back/user/userinfo.jsp";
    }

    /**
     *
     * @param req
     * @return
     */
    public User toUser(HttpServletRequest req) {
        // 1.获取表单数据
        String username = req.getParameter("username");
        String pass = req.getParameter("pass");
        String sex = req.getParameter("sex");
        String email = req.getParameter("email");
        String age = req.getParameter("age");
        // 这里要写上id,因为虽然添加是没有id，但是更新是有id的
        String id = req.getParameter("id");

        // 2.封装
        User user = new User();
        user.setUsername(username);
        user.setPass(pass);
        if (id != null && !"".equals(id)) {
            user.setId(Integer.parseInt(id));
        }
        if (sex != null && !"".equals(sex)) {
            user.setSex(Integer.parseInt(sex));
        }
        if (age != null && !"".equals(age)) {
            user.setAge(Integer.parseInt(age));
        }
        user.setEmail(email);
        return user;
    }

    /**
     * 添加用户的方法
     * @param req
     * @param response
     * @return
     */
    public String addUser(HttpServletRequest req, HttpServletResponse response) {

        User user = toUser(req);

        // 3.调用业务层
        boolean save = userService.save(user);
//        boolean save = false;

        // 4.响应用户
        return Response.out(save, "UserController/userPage");
    }

//    public String out(Boolean flag) { // add,udpate,delete ->写操作
//        if (flag) {
//            // 抽取常量可以避免单词写错
//            return ShopConstants.FORWARD + ":UserController/userPage";
//        } else {
//            return ShopConstants.SCRIPT + ":操作失败"; // 弹框的是提示用户添加失败，页面不要刷新
//        }
//    }

    /**
     * 通过id单个查询用户的方法
     * @param request
     * @param response
     * @return
     */
    public String getUserById(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        User user = userService.byId(Integer.parseInt(id));
        request.setAttribute("user", user);
        return ShopConstants.FORWARD + ":back/user/updateuser.jsp";
    }

    /**
     * 更新用户的方法
     * @param request
     * @param response
     * @return
     */
    public String updateUser(HttpServletRequest request, HttpServletResponse response) {

        // 1.封装数据
        User user = toUser(request); // 获取表单数据，封装

        boolean b = userService.updateById(user);

        return Response.out(b, "UserController/userPage");
    }

    /**
     * 删除用户的方法
     * @param req
     * @param response
     * @return
     */
    public String removeUserById(HttpServletRequest req, HttpServletResponse response) {
        return Response.out(userService.removeById(Integer.parseInt(req.getParameter("id"))),"UserController/userPage");
    }

    /**
     * 删除多行的方法
     * @param request
     * @param response
     * @throws IOException
     */
    public void batchDel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String json = request.getReader().readLine();
        List<String> ids = JSON.parseArray(json, String.class);
        Integer flat = userService.batchDel(ids);

        Map<String, Integer> result = new HashMap<>();
        result.put("code", 100); // 失败
        if (flat >= 0) {
            result.put("code", 200); // 成功
        }

        String jsonString = JSON.toJSONString(result);
        response.getWriter().write(jsonString);

    }
}
